﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace AutoServey
{
    class GetPanoImg
    {
        public void searchPano(string panoPoint,double heading,string xmlPath)
        {
            string key = getKey();
            panoPoint = panoPoint.Replace("),(", ";");
            string[] latlngs = panoPoint.Split(';');
            for (int i = 0; i < latlngs.Length; i++)
            {
                string latlng = latlngs[i];
                if (i == 0)
                {
                    latlng = latlng.Split('(')[1];
                }
                else if (i == latlngs.Length - 1)
                {
                    latlng = latlng.Split(')')[0];
                }
                savePano(xmlPath, latlng, heading, 0, 80, key);
                savePano(xmlPath, latlng, heading-22.5, 0, 80, key);
                savePano(xmlPath, latlng, heading-45, 0, 80, key);
                savePano(xmlPath, latlng, heading+22.5, 0, 80, key);
                savePano(xmlPath, latlng, heading + 45, 0, 80, key);
            }
        }

        public void savePano(string path, string latlng, double heading, double pitch, int fov,string key)
        {
            if (!Directory.Exists(string.Format("{0}/StreetView/{1}", Directory.GetParent(path), latlng)))
            {
                Directory.CreateDirectory(string.Format("{0}/StreetView/{1}", Directory.GetParent(path), latlng));
            }
            string panoPath = string.Format("{0}/StreetView/{1}/{2},{3},{4}.jpg", Directory.GetParent(path), latlng, heading, pitch, fov);
            if (!File.Exists(panoPath))
            {
                string src = string.Format("https://maps.googleapis.com/maps/api/streetview?size=600x300&location={0}&fov={3}&heading={1}&pitch={2}&key={4}", latlng, heading, pitch, fov, key);
                using (Stream stream = WebRequest.Create(src).GetResponse().GetResponseStream())
                {
                    Image a = Image.FromStream(stream);
                    a.Save(panoPath);
                }
            }
        }

        public string getKey()
        {
            string key = "AIzaSyDGhzKeqAr_0-8Bu8doMnQgos265nrt1kM";
            return key;
        }
    }
}
